package com.myebills.ebpsfrontend.cust.maxis;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.ejb.FinderException;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.checkfree.isolutions.compass.utilities.ServletUtilities;
import com.checkfree.isolutions.customer.persist.Account;
import com.checkfree.isolutions.customer.persist.AccountHomeImpl;
import com.checkfree.isolutions.customer.persist.Merchant;
import com.checkfree.isolutions.customer.persist.MerchantHomeImpl;
import com.checkfree.isolutions.customer.persist.User;
import com.checkfree.isolutions.persist.PersistServer;
import com.checkfree.isolutions.utility.CFiError;
import com.ibm.logging.ILogger;
import com.ibm.logging.IRecordType;
import com.myebills.ebpsfrontend.cust.controller.AcctDetails;
import com.myebills.ebpsfrontend.cust.controller.EbppxAcctDetailsDataBean;
import com.myebills.ebpsfrontend.cust.controller.EbppxConstants;
import com.myebills.ebpsfrontend.cust.controller.EbppxCusConstants;
import com.myebills.ebpsfrontend.cust.controller.EbppxCusDBUtil;
import com.myebills.ebpsfrontend.cust.controller.EbppxEcsUser;
import com.myebills.ebpsfrontend.cust.controller.EbppxServlet;
import com.myebills.ebpsfrontend.cust.controller.EbppxTransactionServlet;
import com.myebills.ebpsfrontend.cust.controller.EbppxUrlManager;
import com.myebills.ebpsfrontend.cust.controller.EbppxUtil;
import com.myebills.ebpsfrontend.cust.controller.EncryptionHelper;
import com.myebills.ebpsfrontend.cust.utils.EmailNotification;

public class CusEmailVerificationServlet_v1r00 extends EbppxServlet   {

	private static String hardKey="X2q3j5k6E7r8l93tm2n7H5qp";
	 public void doRequest(
    HttpServletRequest req,
    HttpServletResponse res
    ) throws ServletException, java.io.IOException {

        ILogger trcLogger = getTraceLogger(req);
        final String fName = "doRequest";
     
	
		String status="success";
		String cusDatabase="";
		String emailFlagStatus = "";
		String strAcctExtKey = "";
		String strRegisterDate ="";
		String kenanNo;
		
		Date dateExpiryDate = null;
		Connection connection1 = null;
		Connection connection =null;
		
		EmailNotification emailNotiF = new EmailNotification();
		EbppxAcctDetailsDataBean acctDataBean = new EbppxAcctDetailsDataBean();
		EbppxAcctDetailsDataBean acctDetBean = new EbppxAcctDetailsDataBean();
		AcctDetails acctdetails = new AcctDetails();
		DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        try {
        	
		   
        	activateISeriesEngine(req, fName);
            beginTransaction(req, fName);       
            Date currentDate = new Date();
            String actiStatus =null;
            
            String emailAddrs =EbppxUtil.nullToEmpty(req.getParameter("email"));
            String accountsNo =EbppxUtil.nullToEmpty(req.getParameter("accounts"));
            String accountName=EbppxUtil.nullToEmpty(req.getParameter("name"));
			String emailDecrypt = EncryptionHelper.decrypt(emailAddrs,hardKey);
            String acctNoDecrypt = EncryptionHelper.decrypt(accountsNo,hardKey);
           // connection = EbppxCusDBUtil.getDbConnection();  
            
            connection1 = EbppxCusDBUtil.getKenanDbConnection();        
		    connection1.setAutoCommit(false);
		    
		    connection = EbppxCusDBUtil.getDbConnection();        
		    connection.setAutoCommit(false);
		    
		    String strCategoryDatabase = EbppxCusDBUtil.getCategoryDatabase(connection1);
			cusDatabase = EbppxCusDBUtil.getCusDatabase(connection1,strCategoryDatabase,acctNoDecrypt);
			
			// retrieve kenan acct
			String kenanAccounNo = EbppxCusDBUtil.getKenanAccountNo(connection1,strCategoryDatabase,acctNoDecrypt);
            
            String acctNameDecrypt = EncryptionHelper.decrypt(accountName, hardKey);
            acctDataBean = EbppxCusDBUtil.getLatestEmailDeliveryStatus(connection, acctNoDecrypt);
            
		    acctDetBean = acctdetails.getAcctDetails(acctNoDecrypt);
		    strAcctExtKey = acctDetBean.getAcctId();
			Date dateRegisterDate = acctDataBean.getRegisterDate();
			String strEmailAddrs = acctDataBean.getEmailAdd();		 
			String channelId     = acctDataBean.getUpdateByChannel();
			String userId        = acctDataBean.getUpdateByUser();
			emailFlagStatus      = acctDataBean.getEmailStatus();
 
		    
			
			if(dateRegisterDate != null){
				
				strRegisterDate = df.format(dateRegisterDate);
			}

			if (dateRegisterDate != null) {
				dateExpiryDate = dateRegisterDate;

				Calendar c = Calendar.getInstance();
				c.setTime(dateExpiryDate);
				c.add(Calendar.DATE, 5);
				dateExpiryDate = c.getTime();

			}
			System.out.println("currentDate :"+currentDate);
			System.out.println("dateExpiryDate :"+dateExpiryDate);
		    System.out.println("emailFlagStatus : "+emailFlagStatus);
		    if(!emailFlagStatus.equals("")){
		    	if((!emailFlagStatus.equals("Verification"))){
            	
            	  if(currentDate !=null && dateExpiryDate !=null){
            		  
            		  if(!(currentDate.after(dateExpiryDate))){
            			  
            			  if(strEmailAddrs.equals(emailDecrypt)){
            				  
            				  String strEMailSubsript="1";
      						
            				  if((emailFlagStatus.equals("Update") ||(emailFlagStatus.equals("Subscription")))){
            					  
            					if (EbppxCusDBUtil.checkIfEbillSubsExist(connection1, cusDatabase,strAcctExtKey, strCategoryDatabase)) {
          							
         				    	     EbppxCusDBUtil.updateInfoCustText(connection1, cusDatabase,EbppxConstants.EMAIL_DELIVERY_SUBSCRIPTION, kenanAccounNo);
         				    	    
         	
         						}else{
         							
         							if(strEMailSubsript.equals("1")){
         								
         								EbppxCusDBUtil.insertInfoCustText(connection1, cusDatabase,EbppxConstants.EMAIL_DELIVERY_SUBSCRIPTION,kenanAccounNo);
         								
         								
         							}
         						}
         						
         					   
         					     
         						//send email if user successful activation email delivery.
         						if(EbppxCusDBUtil.checkIfPhysicalBillSubsExist(connection1,cusDatabase,acctDetBean.getAcctId(),strCategoryDatabase)){//this is used to check if the data exist in the info_cust_text table
         							
         								EbppxCusDBUtil.updateInfoCustText(connection1, cusDatabase,EbppxConstants.NO_PHYSICAL_BILL_SUBSCRIPTION, kenanAccounNo);
         							
         						}else{
         							if(strEMailSubsript.equals("1")){
         								
         								EbppxCusDBUtil.insertInfoCustText(connection1, cusDatabase,EbppxConstants.NO_PHYSICAL_BILL_SUBSCRIPTION, kenanAccounNo);
           				
         							
         						}
         							
         						}

         					    acctdetails.updateAcctInfo(connection, strAcctExtKey, strEmailAddrs, "1", strRegisterDate, strRegisterDate, channelId, userId);
         				        actiStatus="1";

         				        emailNotiF.sendEmailNotification(emailDecrypt, emailDecrypt, acctNoDecrypt, acctDetBean.getAcctId(), "", status, acctNameDecrypt, accountName, "", "MOA");
            				  }
            				  
            			  }else{
            				  
            				  actiStatus="0";
            			  }
            			  
            			  
            		  }else{
            			  
            				actiStatus="E";
            		  }
            		  
            		  
            	  }
            	
            	
            
            }else{
            	
            	  actiStatus="0";
            	  System.out.println("verified");
            }
		    } else{
			  actiStatus="0";
        	  System.out.println("incorect no");
		   }
            				
			connection1.commit();//kenan
			connection1.setAutoCommit(true);
			connection.commit();
			connection.setAutoCommit(true);
			commitTransaction(req, fName);
            req.setAttribute("status", actiStatus);
            forwardToMappedUrl(req, res, EbppxConstants.URL_JSP_PARAM);
        }

		catch (Throwable t) {
          if (PersistServer.transactionIsActive()){
				try {
					PersistServer.rollbackTransaction();
				}catch (Exception e) {
				}
			}
            deactivateISeriesEngine(req, fName);
			throw new ServletException(t.toString(), t);
		}
        finally {
            try {
      	
              deactivateISeriesEngine(req, fName);
              if (connection1 != null){
                EbppxCusDBUtil.freeKenanDbConnection(connection1);
              }
              if(connection != null){
                  EbppxCusDBUtil.freeDbConnection(connection);
              }
            }catch (SQLException e1) {
      			
              throw new ServletException(e1);
            }catch (Throwable t1){
      			
              throw new ServletException(t1.toString(), t1);
            }
        }
	}
	

}

    
